﻿using EFCore.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SService;

namespace WMSWeb.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrganizationalStructureController : ControllerBase
    {
        private readonly WmssystemContext myDb;
        private readonly OrganizationalStructureS organizationalStructureS;
        public OrganizationalStructureController(WmssystemContext myDb, SService.OrganizationalStructureS organizationalStructureS)
        {
            this.myDb = myDb;
            this.organizationalStructureS = organizationalStructureS;
        }
        /// <summary>
        /// 组织机构分页查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("FenYe")]
        public async Task<List<Sys_OrganizationalStructure>> FenYe(string Key = null, string Status = null)
        {
            return await organizationalStructureS.FenYe(Key, Status);
        }
        [HttpGet]
        public async Task<List<Sys_jilian>> GetYI()
        {
            List<Sys_OrganizationalStructure> topLevelItems = await organizationalStructureS.YiJi();
            List<Sys_jilian> jilians = new List<Sys_jilian>();
            foreach (Sys_OrganizationalStructure item in topLevelItems)
            {
                Sys_jilian jilian = new Sys_jilian()
                {
                    value = (int)item.O_SSerialId,
                    label = item.O_SOrganizationName,
                    children = await GetChildren(item.O_SSerialId)
                };
                jilians.Add(jilian);
            }
            return jilians;
        }

        private async Task<List<Sys_jilian>> GetChildren(int? parentId)
        {
            List<Sys_OrganizationalStructure> childItems = await organizationalStructureS.Erji((int)parentId);
            List<Sys_jilian> jilians = new List<Sys_jilian>();
            foreach (Sys_OrganizationalStructure item in childItems)
            {
                // 检查是否已经存在相同的节点
                if (!jilians.Any(x => x.value == item.O_SSerialId))
                {
                    Sys_jilian jilian = new Sys_jilian()
                    {
                        value = (int)item.O_SSerialId,
                        label = item.O_SOrganizationName,
                        children = await GetChildren(item.O_SSerialId)
                    };
                    jilians.Add(jilian);
                }
            }
            return jilians;
        }
    }
}
